<?php

namespace Wechat\Controller;

use Org\Net\IpLocation;
use Think\Controller;

class CommonController extends Controller {

    protected $customer;

    function _initialize() {

//        cookie("openid",NULL);

//        cookie("openid", "ohVESv4w-wVhdNbRkhIcFUkYCX5s");

//        cookie("openid", "ohVESv-0VpZZqFOTanJ2T3dHlgkU");

        $host = $_SERVER['HTTP_HOST'];
        $moduleName = strtolower(MODULE_NAME);

        if($host == C("FRONTEND_HOST")
            && $moduleName != "wechat") {
            header("Location:http://".$host."/wechat");
            exit();
        } else if($host == C("BACKEND_HOST")
            && $moduleName != "admin") {
            header("Location:http://".$host."/admin");
            exit();
        } else if($host == C("ROBOT_HOST")
            && $moduleName != "robot") {
            header("Location:http://".$host."/robot");
            exit();
        }

        $callback = 'http://'.$_SERVER['HTTP_HOST']
            .$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

        $str = urlencode($callback);

        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            . C('appid') . '&redirect_uri=' . C('oauthServerUrl')
            .'&response_type=code&scope=snsapi_userinfo&state='
            . $str . '&connect_redirect=1#wechat_redirect';

        $openid = cookie("openid");

        if(isNullOrEmpty($openid)) {
            header("Location: $url");
            exit();
        }

        $currentCustomer = D("Customer")
            ->queryByMap(array("openid"=>$openid));

        if(isNullOrEmpty($currentCustomer)) {

            $currentCustomer = D("Customer")
                ->queryByMap(array("openid"=>$openid));
            if(isNullOrEmpty($currentCustomer)) {
                header("Location: $url");
                exit();
            }

            if($currentCustomer["openid"] != $openid) {
                cookie("openid", null);
                cookie("openid", $currentCustomer["openid"]);
            }

        }


        $this->customer = $currentCustomer;

    }

}